import tkinter as tk
import io
import sys
from calc import print_resistor_pair


def on_submit(event=None):
    value_str = entry.get()
    if not value_str:
        return
    text.tag_remove("highlight", "1.0", "end")
    try:
        value = float(value_str)
    except ValueError:
        text.insert(tk.END, "错误：请输入一个有效的浮点数\n")
        text.tag_add("highlight", "end-2l linestart", "end-1l lineend")
        text.yview_moveto(1)
        return
    # 重定向标准输出到字符串缓冲区
    sys.stdout = io.StringIO()
    print_resistor_pair(value)
    # 获取缓冲区中的文本并显示在文本框中
    s = sys.stdout.getvalue()
    text.insert(tk.END, s)
    line_count = s.count('\n')
    text.tag_add("highlight", f"end-{line_count + 1}l linestart", "end-1l lineend")
    text.yview_moveto(1)
    # 恢复标准输出
    sys.stdout = sys.__stdout__

root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
label = tk.Label(frame, text="输入一个参数")
label.pack(side=tk.LEFT)
entry = tk.Entry(frame)
entry.pack(side=tk.LEFT)
entry.bind("<Return>", on_submit)
entry.focus_set()
submit = tk.Button(frame, text="计算", command=on_submit)
submit.pack(side=tk.LEFT)
text = tk.Text(root)
text.pack()
text.tag_config("highlight", background="yellow", foreground="purple")
text.tag_config("gray", foreground="gray")
# text.bind("<1>", lambda event: text.tag_remove("highlight", "1.0", "end"))
root.mainloop()